package com.hzlh.core.service.impl;


import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.hzlh.core.domain.UploadedFile;
import com.hzlh.core.service.SystemParameterService;
import com.hzlh.core.service.UploadService;
import com.hzlh.core.utils.DateUtils;
import com.hzlh.core.utils.FtpUtils;


@Service
public class UploadFtpService implements UploadService {
	private static Logger logger = Logger.getLogger(UploadService.class);

	@Autowired
	private SystemParameterService systemParameterService;


	/**
	 * 上传内部实现类
	 * <p>
	 *
	 * @param mfile
	 * @param uploadRootDir
	 *            上传的根目录
	 * @param uploadFirstSubDir
	 *            上传的第一层子目录
	 * @return
	 */
	private UploadedFile uploadFile(MultipartFile mfile, String uploadRootDir, String uploadFirstSubDir) {
		String uploadSubDir = getUploadFullPath(uploadFirstSubDir);// 上传全子目录
		UploadedFile retrunO = null;
		if (mfile != null && mfile.getSize() > 0) {
			String fileOriginalName = mfile.getOriginalFilename();// 原始文件名
			String fileUploadedName = getUploadedName(fileOriginalName);// 上传之后的文件名

			// 上传之后返回上传的信息
			retrunO = new UploadedFile();
			retrunO.setUploadRootDir(uploadRootDir);// 上传根目录
			retrunO.setFileUploadedName(fileUploadedName);// 上传之后的文件名
			retrunO.setFileOriginalName(fileOriginalName);//原始文件名
			retrunO.setUploadSubDir(uploadSubDir);// 上传的子目录
			retrunO.setFileSize(mfile.getSize() / 1000);
			retrunO.setReadUrl(uploadSubDir + fileUploadedName);

			if (logger.isDebugEnabled()) {
				logger.debug("upload file [" + retrunO.getUploadFullPath() + "]");
			}
			String path = uploadRootDir+uploadSubDir;//上传全路径
			try {
				InputStream input = mfile.getInputStream();
				FtpUtils.uploadFile(systemParameterService.getFtpUrl(), new Integer(systemParameterService.getFtpPort()).intValue(), 
						systemParameterService.getFtpUsername(), systemParameterService.getFtpPassword(), 
						path, fileUploadedName, input);
				
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				logger.error(e1);
				throw new IllegalStateException(e1);
			}
			
		}

		return retrunO;

	}

	/**
	 * 上传到正式目录
	 * <p>
	 *
	 * @param uploadFirstSubDir
	 *            上传的第一层子目录
	 * @param mfile
	 * @return
	 */
	public UploadedFile uploadFileToUploadDir(String uploadFirstSubDir, MultipartFile mfile) {
		return uploadFile(mfile, getUploadRootDir(), uploadFirstSubDir);
	}

	/**
	 * 上传到临时目录
	 * <p>
	 *
	 * @param mfile
	 * @return
	 */
	public UploadedFile uploadFileTempDir(MultipartFile mfile) {
		return uploadFile(mfile, getUploadTempRootDir(), "");
	}

	@Override
	public boolean deleteFile(String fileReadPath) {
		boolean r = false;
		return r;
	}

	/**
	 * 上传之后的名称
	 * <p>
	 *
	 * @param fileOriginalName
	 * @return
	 */
	private String getUploadedName(String fileOriginalName) {
		UUID uuid = UUID.randomUUID();
		String fileUploadedName = uuid.toString()
				+ StringUtils.substring(fileOriginalName, StringUtils.lastIndexOf(fileOriginalName, '.'));

		return fileUploadedName;
	}

	/**
	 * 创建上传的全目录(在根目录下建立子目录),并范围子目录路径
	 * <p>
	 *
	 * @param uploadRootDir
	 * @return
	 */
	public static String getUploadFullPath(String uploadType) {
		Date today = DateUtils.getCurrentDate();

		if (StringUtils.isNotBlank(uploadType)) {
			uploadType = "/" + uploadType;
		}

		String s = uploadType
				+ "/" + DateUtils.formatDate("yyyyMM", today)
				+ "/" + DateUtils.formatDate("dd", today)
				+ "/" + DateUtils.formatDate("HH", today) + "/";
		return s;
	}



	/**
	 * 获取上传文件的根目录
	 * <p>

	 *
	 * @return
	 */
	public String getUploadRootDir() {
		return systemParameterService.getFileServerDir() + UPLAOD_PATH;
	}

	/**
	 * 获取上传文件的URL
	 */
	public String getUploadUrl() {
		return systemParameterService.getFileServerUrl() + UPLAOD_PATH;
	}

	/**
	 * 获取上传文件的临时根目录
	 * <p>
	 *
	 * @return
	 */
	public String getUploadTempRootDir() {
		return getUploadRootDir() + UPLAOD_TEMP;
	}

	/**
	 * 获取上传临时文件的URL
	 */
	public String getUploadTempUrl() {
		return getUploadUrl() + UPLAOD_TEMP;
	}

	@Override
	public String convertTempPathToUploadPath(String tempPath, String newPath) {
		return tempPath.replace(UPLAOD_TEMP, newPath);
	}

	@Override
	public String buildImage(String origUrl, int width, int height) {

		return null;
	}

	public static String fileNameAddSuffix(String fileName, String suffix) {
		int p = fileName.lastIndexOf(".");
		String fileName1 = fileName.substring(0, p);
		String extName = fileName.substring(p);
		return fileName1 + suffix + extName;
	}
	/**
	 * 生产文件名
	 * <p>
	 *
	 * @param uploadRootDir
	 * @return
	 */
	public static String getfileName(String filename,String suffixName) {
		Date today = DateUtils.getCurrentDate();


		String s = filename+ DateUtils.formatDate("yyyyMM", today)+ DateUtils.formatDate("dd", today)+ DateUtils.formatDate("HH", today)+DateUtils.formatDate("SS", today)+"."+suffixName;
		return s;
	}
	/**
	 * 生产文件名，修改文件名，但不用时间格式化
	 * <p>
	 *
	 * @param uploadRootDir
	 * @return
	 */
	public static String getfileName(String filename,String suffixName,String key) {
		String s = suffixName+filename;
//		String mString="";
//			if (StringUtils.isNotBlank(s)) {
//				mString =  URLEncoder.encode(s);
//			}
		
		return s;
	}

}
